package com.systemsjr.mpf.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class MpfConnector {

	private static final String DATABASE_NAME = "FinanceManager";
	private SQLiteDatabase database;
	private MpfDbOpenHelper databaseOpenHelper;

	public MpfConnector(Context context) {
		databaseOpenHelper = new MpfDbOpenHelper(context, DATABASE_NAME, null, 1);
	}

	public void open() throws SQLException {
		if (database == null) {
			database = databaseOpenHelper.getWritableDatabase();
		}
	}

	public void close() {
		if (database != null) {
			database.close();
		}
	}

	public void insert(String tableName, String nullColumnHack,
			ContentValues contentValues) {
		
		open();
		database.insert(tableName, nullColumnHack, contentValues);
		close();
	}
	
	public void update(String tableName, ContentValues contentValues, long id) {
		
		open();
		database.update(tableName, contentValues, " _id=" + id, null);
		close();
	}

	public Cursor get(String table, String[] columns, String where) {

		String sql = "SELECT ";
		
		for(int i = 0; i < columns.length - 1; i++){
			sql = sql + columns[i] + ",";
		}
		
		sql = sql + columns[columns.length-1] + " from " + table + " " + where;
		open();
		return database.rawQuery(sql, null);
	}

}
